const electron = require('electron');
const path = require('path');
const fs = require('fs');

const { app } = electron;

const isWin = process.platform === 'win32';

function applySettings() {

    var csettings = {};

    const file = appdata('cache', 'settings.json');
    if (fs.existsSync(file)) {
        let content = fs.readFileSync(file, 'utf-8');
        content = (content || '').trim();

        if (content && (content.startsWith('{') && content.endsWith("}"))) {
            try {
                csettings = JSON.parse(content);
            } catch (ex) {
                console.log(ex);
            }
        }
    }

    global.settings = csettings;

    if (isWin && (!csettings || !csettings.EnableMediaFoundation)) {
        console.log('set disable Media Foundation');
        app.commandLine.appendSwitch('disable-features=MediaFoundationVideoCapture');
    }

    if (csettings && csettings.DisableAcceleratedVideo) {
        console.log('disable accelerated video');
        app.commandLine.appendSwitch('disable-accelerated-video');
    }

    if (csettings && (process.env.KOOLEARN_DISABLE_ACCELERATED || csettings.DisableHardwareAcceleration)) {
        console.log('disable accelerated');
        app.disableHardwareAcceleration();
    }
}

function appdata(...paths) {
    const appname = global.appname;
    let appdata = app.getPath('appData');

    if (!appdata) {
        if (isWin) {
            appdata = process.env.appdata || `${process.env.USERPROFILE}\\AppData\\Roaming`;
        } else if (process.platform == 'darwin') {
            appdata = path.join(process.env.HOME, 'Library/Application Support/');
        }
    }

    console.log(appdata, ",", appname, ",", paths);

    appdata = path.join(appdata, appname, appname, ...paths);
    return appdata;
}

module.exports = { applySettings };